{$IFDEF FPC}{$mode objfpc}{$ENDIF}
unit CgiUtils;
interface
uses qstrparser, tagparser;

Type
    TQSproc   = Procedure(value: widestring; var BreakQueue: Boolean);

Var
   CGIpage    : widestring ='';

Procedure CGIinit; overload;
Procedure CGIinit(GET,POST: widestring); overload;
Function CGIQS: TQSTR;            //CGI QueryString
Function OutPage: integer;        //prints the page out to the output and returns number of bytes
Function TryCGIproc(paramID: widestring; QSproc: TQSproc): Boolean;

implementation
Const
    HTMLheader    = 'Content-type:text/html'+#10+#13;


var
    T             : TQSTR = nil;
    QSBlock       : Boolean = false;

Function TryCGIproc(paramID: widestring; QSproc: TQSproc): Boolean;
  var v: widestring;
  begin
   Result:=False;
   if(QSBlock)then exit;
   v:=CGIQS.Params[paramID];
   Result:=(v<>QSTR_error);
   if not Result then exit;
   if Assigned(QSproc)then QSproc(v,QSblock) else Result:=false;
  end;


Function OutPage: integer;
  begin
    writeln(HTMLheader);
    writeln(CGIpage);
    Result:=Length(HTMLheader)+Length(CGIpage);
  end;

Function CGIQS: TQSTR;
  begin
   Result:=T;
  end;


Procedure CGIinit;
  begin
   T:=TQSTR.Create;
  end;
Procedure CGIinit(GET,POST: widestring);
  begin
    T:=TQSTR.Create(GET,POST);
  end;

initialization
  CGIpage:='';
finalization
  if(T<>nil)then T.Free;
end.
